import axios from 'axios'
import { Message } from 'element-ui'

import store from '@/store'
// 根据环境不同引入不同api地址
import { baseApi } from '@/config'
import { getToken, removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: baseApi, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000, // request timeout
  // method: 'post',
  transformRequest: [function(data) {
    return JSON.stringify(data)
  }],
  headers: {
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // please modify it according to the actual situation
    config.headers['token'] = getToken()
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (res.code === -9000) {
      removeToken()
      this.$router.push(`/login`)
      return Promise.reject('请重新登录')
    } else {
      // console.log(res)
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
